package com.lyl.commonutils.redis;

import com.lyl.exception.ZxjyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


public class RedisUtils {

    public static long incr(RedisTemplate redisTemplate,String key, long delta){
        if(delta<0){
            throw new ZxjyException("递增因子必须大于0");
        }
        // 如果不存在就设置
        redisTemplate.opsForValue().setIfAbsent(key, "0", 26 , TimeUnit.HOURS);
        return redisTemplate.opsForValue().increment(key,delta);
    }

    public static void setDataBase(RedisTemplate redisTemplate, Integer num) {
        if (num == null || num > 15 || num < 0) {
            num = 0;
        }
        LettuceConnectionFactory connectionFactory = (LettuceConnectionFactory) redisTemplate.getConnectionFactory();
        if (connectionFactory != null && num != connectionFactory.getDatabase()) {
            connectionFactory.setDatabase(num);
            redisTemplate.setConnectionFactory(connectionFactory);
            connectionFactory.afterPropertiesSet();
            connectionFactory.resetConnection();

        }
    }
}
